<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>更新页面</title>
    <link rel="stylesheet" href="/app/admin/component/pear/css/pear.css" />
    <link rel="stylesheet" href="/app/admin/component/jsoneditor/css/jsoneditor.css" />
    <link rel="stylesheet" href="/app/admin/admin/css/reset.css" />

</head>
<body>

<form class="layui-form">

    <div class="mainBox">
        <div class="main-container mr-5 content_html" style="display: flex;flex-direction: column;">
            <!--<div style="width: 90%;display: flex;flex-direction: row-reverse;">-->
                <!--<label class="layui-form-label" style="width: auto">:提问</label>-->
                <!--<div class="" style="line-height: 35px;background-color: #7bcd7d;padding: 0 5px;margin: 5px 0">-->
                    <!--大苏打大苏打大苏打大苏打大苏打大苏打大苏打大苏打大苏打大苏打大苏打大苏打大苏打-->
                <!--</div>-->
            <!--</div>-->
            <!--<div style="width: 90%;display: flex;flex-direction: row;">-->
                <!--<label class="layui-form-label" style="width: 100px">回答:</label>-->
                <!--<div class="" style="line-height: 35px;background-color: #e7e5e5;padding: 0 5px;margin: 5px 0">-->
                    <!--=====<br/>   - 👨\u200d🎨 人物: 姜凡，一位目光坚定、充满智慧的年轻男子，身姿挺拔，面容刚毅，透露出自信和决心。<br/>   - 🌆 场景: 未来科技感十足的虚拟空间，光线交错，数据流动。<br/>   - 🎨 物品: 手腕上闪烁着蓝光的科技系统手环，屏幕上显示着复杂的数据和图案。<br/>   - 🌈 色彩: 以冷色调为主，蓝色和银色交织，营造出神秘的科技氛围。<br/>   - 🌬️ 氛围: 充满未知与探索，紧张而又充满希望。<br/>=====-->
                <!--</div>-->
            <!--</div>-->

        </div>
    </div>

    <div class="bottom">
        <div class="button-container" style="width: 96%;display: flex;flex-direction: row;justify-content: space-between;align-items:center;height: 50px">
            <div style="width: 92%;">
                <label class="layui-form-label">提问:</label>
                <div class="layui-input-block">
                    <input type="text" name="question" placeholder="" class="layui-input">
                </div>
            </div>
            <button type="submit" class="pear-btn pear-btn-primary pear-btn-md" lay-submit="" lay-filter="save">
                提交
            </button>
            <!--<button type="reset" class="pear-btn pear-btn-md">-->
            <!--重置-->
            <!--</button>-->
        </div>
    </div>

</form>

<script src="/app/admin/component/layui/layui.js?v=2.8.12"></script>
<script src="/app/admin/component/pear/pear.js"></script>
<script src="/app/admin/component/jsoneditor/jsoneditor.js"></script>
<script src="/app/admin/admin/js/permission.js"></script>
<script src="/app/admin/admin/js/functions.js"></script>
<script src="/app/admin/admin/js/md5.js"></script>

<script>

    // 相关接口
    const CONTENT_VALUE = layui.url().search['content']||'';
    const AISESSION_API = "/app/admin/plan/part/aisession";

    //提交事件
    layui.use(["form", "popup"], function () {
        layui.$('input[name="question"]').val(decodeURI(CONTENT_VALUE));

        layui.form.on("submit(save)", function (data) {
            if(data.field['question']==false){
                layer.msg('提问不能为空',{icon:2,time:1000});
                return false;
            }

            let html = '<div style="width: 90%;display: flex;flex-direction: row-reverse;">\n' +
                '                <label class="layui-form-label" style="width: auto">:提问</label>\n' +
                '                <div class="" style="line-height: 35px;background-color: #7bcd7d;padding: 0 5px;margin: 5px 0">\n' +
                '                    '+data.field['question']+'\n' +
                '                </div>\n' +
                '            </div>';
            layui.$('.content_html').append(html);

            const streamUrl = 'https://api.coze.cn/v3/chat';

            // 创建Headers对象
            const headers = new Headers({
                'Content-Type': 'application/json',
                'Accept': 'text/event-stream',
                'Authorization': 'Bearer pat_K6YkH5ECCC6vZa7z9OgWGJGiHNZCzy4JC9lVXcb0pzQbmyJCPC5xKvO5MPguqo0X'
            });

            // 发起POST请求获取流媒体数据
            let vs = {
                method: "POST",
                headers: headers,
                body: JSON.stringify({
                    "bot_id": "7389148622644281380",
                    "user_id": "2010008428",
                    "stream": true,
                    "auto_save_history": false,
                    "additional_messages": [
                        {
                            "role": "user",
                            "content": data.field['question'],
                            "content_type": "text"
                        }
                    ]
                })
            }
            fetch(streamUrl, vs)
                .then(response => {
                    // 确保服务器响应的类型是流
                    if (!response.body) {
                        throw new Error('流不可用');
                    }
                    return response.body;
                })
                .then(stream => {
                    // 创建一个ReadableStream实例来处理数据流
                    const reader = stream.getReader();

                    const timestamp = new Date().getTime();
                    let classVal = 'content_answer_'+timestamp;
                    let html = ' <div style="width: 90%;display: flex;flex-direction: row;">\n' +
                        '                <label class="layui-form-label" style="width: 100px">回答:</label>\n' +
                        '                <div class="'+classVal+'" style="line-height: 35px;background-color: #e7e5e5;padding: 0 5px;margin: 5px 0">\n' +
                        '                    '+
                        '                </div>\n' +
                        '            </div>';
                    layui.$('.content_html').append(html);
                    layui.$('input[name="question"]').val('');

                    // 定义数据处理函数
                    const pump = () => {
                        return reader.read().then(({ value, done }) => {
                            if (done) {
                                return;
                            }
                            // 处理流数据（value）
                            //console.log(value);
                            // 处理流中的数据（例如，将其转换为字符串）
                            const chunk = new TextDecoder('utf-8').decode(value);

                            let datas = chunk.split("\n");
                            let rows = [];
                            layui.each(datas ,function (i,v) {
                               if(v=="event:conversation.message.delta"){

                                   let jsonStr = datas[parseInt(i)+1].substring(5);
                                   let jsonData = JSON.parse(jsonStr);
                                   let str = jsonData['content'].replace("\n","<br/>")

                                   let text = layui.$('.'+classVal).html();
                                   text += str;
                                   layui.$('.'+classVal).html(text);
                                   console.log(classVal)
                               }
                            })


                            //console.log(datas); // 输出流中的数据
                            // 递归调用pump来读取更多数据
                            pump();
                        });
                    };

                    // 开始读取流数据
                    pump();
                })
                .catch(error => {
                    layer.msg('请求流时发生错误:'+error.toString(),{icon:2,time:2000});
                    //console.error('请求流时发生错误:', error);
                });

            // let loading = layer.load();
            // layui.$.ajax({
            //     url: AISESSION_API,
            //     type: "POST",
            //     dateType: "json",
            //     data: data.field,
            //     async:true,
            //     headers: get_header(data.field),
            //     success: function (res) {
            //         layer.close(loading);
            //
            //         if (res.code) {
            //             return layui.popup.failure(res.msg);
            //         }
            //
            //         let html = ' <div style="width: 90%;display: flex;flex-direction: row;">\n' +
            //             '                <label class="layui-form-label" style="width: 100px">回答:</label>\n' +
            //             '                <div class="" style="line-height: 35px;background-color: #e7e5e5;padding: 0 5px;margin: 5px 0">\n' +
            //             '                    ' +res.data['content']+
            //             '                </div>\n' +
            //             '            </div>';
            //         layui.$('.content_html').append(html);
            //
            //         layui.$('input[name="question"]').val('');
            //     }
            // });
            return false;
        });
    });

</script>

</body>

</html>
